package com.yang.inventorymanagement.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.inventorymanagement.pojo.User;
import com.yang.inventorymanagement.service.UserService;
import com.yang.inventorymanagement.mapper.UserMapper;
import com.yang.inventorymanagement.utils.SessionUtils;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-12-22 09:39:35
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    /**
     * 用户登录
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public boolean userLogin(String userName, String password) {
        if (userName == null || "".equals(userName)) {
            return false;
        }
        String passwordMd5 = DigestUtil.md5Hex(password);
        QueryWrapper<User> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", userName);
        usersQueryWrapper.eq("password", passwordMd5);
        User users = this.getOne(usersQueryWrapper);
        if (users != null) {
            //保存用户信息到session
            SessionUtils.getSession().put("user", users);
            return true;
        }
        return false;
    }

    /**
     * 退出登录，模拟登录
     *
     * @return
     */
    @Override
    public boolean loginOut() {
        //退出登录，删除session中用户信息
        Object remove = SessionUtils.getSession().remove("user");
        if (remove != null) return true;
        return false;
    }

    /**
     * 修改用户密码 ,修改失败返回0，修改成功返回1
     *
     * @param id
     * @return
     */
    @Override
    public int updateUserPasswordById(String id, String password) {
        if (password == null || "".equals(password)) {
            return 0;
        }
        if (id == null || "".equals(password)) {
            return 0;
        }
        User user = new User();
        user.setPassword(DigestUtil.md5Hex(password));
        user.setUserid(Integer.valueOf(id));
        int i = baseMapper.updateById(user);
        return i;
    }

    @Override
    public int insertUser(User user) {
        if (user == null) {
            return 0;
        }
        String password = user.getPassword();
        user.setPassword(DigestUtil.md5Hex(password));
        int insert = baseMapper.insert(user);
        return insert;
    }

}




